<template>
  <div class="dashboard">
    <el-container style="height: 100vh;">
      <el-aside width="auto">
        <div class="sidebar-container">
          <el-menu
              :collapse="isCollapse"
              :default-active="activeMenu"
              active-text-color="#409EFF"
              background-color="#001529"
              class="side-menu"
              router
              text-color="#fff"
          >
            <div class="logo-container">
              <el-icon v-if="isCollapse">
                <Ticket/>
              </el-icon>
              <span v-else>财务共享中心</span>
            </div>

            <!-- 订单管理菜单 -->
            <el-sub-menu index="order">
              <template #title>
                <el-icon>
                  <ShoppingCart/>
                </el-icon>
                <span>订单管理</span>
              </template>
              <el-menu-item index="/dashboard/order-list">
                <el-icon>
                  <List/>
                </el-icon>
                <span>订单列表</span>
              </el-menu-item>
              <el-menu-item index="/dashboard/order-create">
                <el-icon>
                  <Plus/>
                </el-icon>
                <span>创建订单</span>
              </el-menu-item>
              <el-menu-item index="/dashboard/order-statistics">
                <el-icon>
                  <Histogram/>
                </el-icon>
                <span>订单统计</span>
              </el-menu-item>
            </el-sub-menu>

            <!-- 收货单管理菜单 -->
            <el-sub-menu index="receipt">
              <template #title>
                <el-icon>
                  <Box/>
                </el-icon>
                <span>收货单管理</span>
              </template>
              <el-menu-item index="/dashboard/receipt-list">
                <el-icon>
                  <List/>
                </el-icon>
                <span>收货单列表</span>
              </el-menu-item>
              <el-menu-item index="/dashboard/receipt-create">
                <el-icon>
                  <Plus/>
                </el-icon>
                <span>创建收货单</span>
              </el-menu-item>
              <el-menu-item index="/dashboard/receipt-statistics">
                <el-icon>
                  <Histogram/>
                </el-icon>
                <span>收货单统计</span>
              </el-menu-item>
            </el-sub-menu>

            <!-- 发票管理菜单 -->
            <el-sub-menu index="invoice">
              <template #title>
                <el-icon>
                  <Document/>
                </el-icon>
                <span>发票管理</span>
              </template>
              <el-menu-item index="/dashboard/invoice-list">
                <el-icon>
                  <List/>
                </el-icon>
                <span>发票列表</span>
              </el-menu-item>
              <el-menu-item index="/dashboard/invoice-add">
                <el-icon>
                  <Plus/>
                </el-icon>
                <span>创建发票</span>
              </el-menu-item>
              <el-menu-item index="/dashboard/invoice-statistics">
                <el-icon>
                  <Histogram/>
                </el-icon>
                <span>发票统计</span>
              </el-menu-item>
            </el-sub-menu>

            <!-- 三单匹配菜单 -->
            <el-sub-menu index="match">
              <template #title>
                <el-icon>
                  <Connection/>
                </el-icon>
                <span>三单匹配</span>
              </template>
              <el-menu-item index="/dashboard/match/integrated">
                <el-icon>
                  <Connection/>
                </el-icon>
                <span>三单匹配</span>
              </el-menu-item>
              <el-menu-item index="/dashboard/match/matched">
                <el-icon>
                  <List/>
                </el-icon>
                <span>已匹配订单</span>
              </el-menu-item>
              <el-menu-item index="/dashboard/match-statistics">
                <el-icon>
                  <DataAnalysis/>
                </el-icon>
                <span>匹配统计</span>
              </el-menu-item>
            </el-sub-menu>
          </el-menu>

          <div class="toggle-button" @click="toggleCollapse">
            <el-icon>
              <component :is="isCollapse ? 'Expand' : 'Fold'"/>
            </el-icon>
          </div>
        </div>
      </el-aside>

      <el-container>
        <el-header class="main-header">
          <div class="header-left">
            <el-breadcrumb>
              <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
              <el-breadcrumb-item>{{ pageTitle }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>

          <div class="header-right">
            <el-dropdown>
              <span class="dropdown-link">
                <el-avatar :size="32" icon="User"/>
                <span class="username">{{ realName }}</span>
                <el-icon><ArrowDown/></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="changePassword">
                    <el-icon>
                      <Lock/>
                    </el-icon>
                    修改密码
                  </el-dropdown-item>
                  <el-dropdown-item divided @click="handleLogout">
                    <el-icon>
                      <SwitchButton/>
                    </el-icon>
                    退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>

        <el-main class="main-content">
          <router-view></router-view>
        </el-main>

        <el-footer class="main-footer">
          财务共享中心 ©{{ new Date().getFullYear() }} 版权所有
        </el-footer>
      </el-container>
    </el-container>

    <!-- 修改密码对话框 -->
    <el-dialog
        v-model="passwordDialogVisible"
        title="修改密码"
        width="400px"
    >
      <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          label-width="100px"
      >
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input
              v-model="passwordForm.currentPassword"
              show-password
              type="password"
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
              v-model="passwordForm.newPassword"
              show-password
              type="password"
          />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
              v-model="passwordForm.confirmPassword"
              show-password
              type="password"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button
              :loading="passwordChangeLoading"
              type="primary"
              @click="handlePasswordChange"
          >
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {computed, onMounted, ref} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {ElMessage, ElMessageBox} from 'element-plus';
import {
  ArrowDown,
  Box,
  Connection,
  DataAnalysis,
  Document,
  Histogram,
  List,
  Lock,
  Plus,
  ShoppingCart,
  SwitchButton,
  Ticket
} from '@element-plus/icons-vue';
import {changePassword as apiChangePassword, getUserInfo, logout} from '../api/user';
import {clearAuthStorage} from '../utils/storage';

const router = useRouter();
const route = useRoute();

// 侧边栏折叠状态
const isCollapse = ref(false);
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value;
};

// 当前用户信息
const username = ref('');
const realName = ref('');

// 当前活动菜单项
const activeMenu = computed(() => route.path);

// 页面标题
const pageTitle = computed(() => {
  const path = route.path;
  if (path.includes('order-list')) return '订单列表';
  if (path.includes('order-create')) return '创建订单';
  if (path.includes('order-statistics')) return '订单统计';
  if (path.includes('order-edit')) return '编辑订单';
  if (path.includes('order-detail')) return '订单详情';
  if (path.includes('receipt-list')) return '收货单列表';
  if (path.includes('receipt-create')) return '创建收货单';
  if (path.includes('receipt-statistics')) return '收货单统计';
  if (path.includes('receipt-edit')) return '编辑收货单';
  if (path.includes('receipt-detail')) return '收货单详情';
  if (path.includes('invoice-list')) return '发票列表';
  if (path.includes('invoice-add')) return '新增发票';
  if (path.includes('invoice-edit')) return '编辑发票';
  if (path.includes('invoice-detail')) return '发票详情';
  if (path.includes('invoice-statistics')) return '发票统计';
  if (path.includes('match/three-way')) return '三单匹配';
  if (path.includes('match-statistics')) return '匹配统计';

  // 新增的匹配页面路径
  if (path === '/dashboard/match') return '匹配管理';
  if (path.includes('match/available')) return '可匹配订单';
  if (path.includes('match/matched')) return '已匹配订单';
  if (path.includes('match/detail')) return '匹配详情';

  return '首页';
});

// 修改密码对话框
const passwordDialogVisible = ref(false);
const passwordChangeLoading = ref(false);
const passwordFormRef = ref();
const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 密码表单验证规则
const passwordRules = {
  currentPassword: [
    {required: true, message: '请输入当前密码', trigger: 'blur'}
  ],
  newPassword: [
    {required: true, message: '请输入新密码', trigger: 'blur'},
    {min: 6, message: '密码长度至少为6个字符', trigger: 'blur'}
  ],
  confirmPassword: [
    {required: true, message: '请确认新密码', trigger: 'blur'},
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// 打开修改密码对话框
const changePassword = () => {
  passwordDialogVisible.value = true;
  // 重置表单
  passwordForm.value = {
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  };

  // 需要在下一个事件循环中重置表单验证结果
  setTimeout(() => {
    passwordFormRef.value?.resetFields();
  }, 0);
};

// 处理密码修改
const handlePasswordChange = async () => {
  if (!passwordFormRef.value) return;

  try {
    await passwordFormRef.value.validate();
    passwordChangeLoading.value = true;

    // 发送修改密码请求
    const response = await apiChangePassword(
        passwordForm.value.currentPassword,
        passwordForm.value.newPassword
    );

    if (response && (response.code === 200 || response.success)) {
      ElMessage.success('密码修改成功');
      passwordDialogVisible.value = false;
    } else {
      ElMessage.error((response && response.message) || '修改密码失败，请检查当前密码是否正确');
    }
  } catch (error) {
    console.error('修改密码失败:', error);
    ElMessage.error('修改密码失败，请检查当前密码是否正确');
  } finally {
    passwordChangeLoading.value = false;
  }
};

// 退出登录
const handleLogout = () => {
  ElMessageBox.confirm(
      '确认退出登录吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        // 调用登出API
        logout().then(() => {
          // 清除token和相关信息
          clearAuthStorage();
          router.push('/login');
          ElMessage.success('已退出登录');
        }).catch(error => {
          console.error('退出失败:', error);
          // 即使API调用失败，也清除本地存储并跳转
          clearAuthStorage();
          router.push('/login');
          ElMessage.success('已退出登录');
        });
      })
      .catch(() => {
        // 取消操作
      });
};

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getUserInfo();
    if (res.code === 200 && res.data) {
      username.value = res.data.username || '';
      realName.value = res.data.realName || '用户';
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    realName.value = '用户';
  }
};

onMounted(() => {
  // 获取用户信息
  fetchUserInfo();
});
</script>

<style scoped>
.sidebar-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #001529;
}

.side-menu {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  border-right: none;
}

.side-menu:not(.el-menu--collapse) {
  width: 200px;
}

.logo-container {
  height: 56px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-size: 18px;
  font-weight: bold;
  padding: 0 20px;
  overflow: hidden;
  white-space: nowrap;
  background: #001529;
  border-bottom: 1px solid #002b42;
}

.toggle-button {
  height: 40px;
  background: #001529;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  cursor: pointer;
  font-size: 16px;
  margin-top: auto;
  border-top: 1px solid #002b42;
}

.main-header {
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  height: 60px !important;
  background: #1890FF;
  background-image: linear-gradient(to right, #1890FF, #36A9FF);
  color: white;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
}

.dropdown-link {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 0 8px;
  color: white;
}

.username {
  margin: 0 8px;
}

.main-content {
  background-color: #f0f2f5;
  padding: 20px;
  height: calc(100vh - 60px - 40px);
  overflow-y: auto;
}

.main-footer {
  height: 40px !important;
  line-height: 40px;
  text-align: center;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
  background-color: #fff;
}

:deep(.el-breadcrumb__item) {
  color: white !important;
}

:deep(.el-breadcrumb__inner) {
  color: white !important;
}

:deep(.el-breadcrumb__separator) {
  color: white !important;
}

:deep(.el-menu--collapse) .el-menu-item span,
:deep(.el-menu--collapse) .el-sub-menu__title span {
  display: none;
}

:deep(.el-menu--collapse) .el-menu-item .el-icon,
:deep(.el-menu--collapse) .el-sub-menu__title .el-icon {
  margin: 0;
}
</style> 